package com.lineage.server.timecontroller.skill;

import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_OwnCharStatus2;
import com.lineage.server.serverpackets.S_PacketBox;
import com.lineage.server.serverpackets.S_SPMR;
import com.lineage.server.serverpackets.S_SkillSound;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.types.Point;
import com.lineage.server.world.World;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BraveAvatarTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(BraveAvatarTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 5000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 5000L, 5000L);
  }
  
  public void run() {
    try {
      Iterator<L1PcInstance> iterator = World.get().getAllPlayers().iterator();
      while (iterator.hasNext()) {
        L1PcInstance pc = iterator.next();
        if (pc == null || 
          pc.getNetConnection() == null)
          continue; 
        if (pc.getParty() != null) {
          L1PcInstance leader = pc.getParty().getLeader();
          if (leader.isCrown() && leader.isSkillMastery(119) && 
            leader.getLocation().getTileLineDistance((Point)pc.getLocation()) <= 16) {
            if (pc.getParty().getNumOfMembers() < 2 || pc.hasSkillEffect(8065))
              continue; 
            pc.setSkillEffect(8065, 0);
            pc.addStr(1);
            pc.addDex(1);
            pc.addInt(1);
            pc.addMr(10);
            pc.addRegistStun(2);
            pc.addRegistSustain(2);
            pc.sendPackets((ServerBasePacket)new S_SPMR(pc));
            pc.sendPackets((ServerBasePacket)new S_OwnCharStatus2(pc));
            pc.sendPacketsAll((ServerBasePacket)new S_SkillSound(pc.getId(), 9009));
            pc.sendPackets((ServerBasePacket)new S_PacketBox(180, 1, 479));
            continue;
          } 
          if (leader.getLocation().getTileLineDistance((Point)pc.getLocation()) <= 16 || 
            !pc.hasSkillEffect(8065))
            continue; 
          pc.removeNoTimerSkillEffect(8065);
          continue;
        } 
        if (!pc.hasSkillEffect(8065))
          continue; 
        pc.removeNoTimerSkillEffect(8065);
      } 
    } catch (Exception e) {
      _log.error("王者加护时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      BraveAvatarTimer braveAvatarTimer = new BraveAvatarTimer();
      braveAvatarTimer.start();
    } 
  }
}
